import { ArticleList, Channel } from '@/types/data'
import { RootAction } from '@/types/store'
import sortBy from 'lodash/sortBy'
type HomeState = {
  channels: Channel[]
  restChannels: Channel[]
  activeId: number
  // 所有频道的文章类型
  channelsArticle: {
    // 索引类型,不知道属性具体指向谁时,使用索引类型
    [key in number]?: ArticleList
  }
}

const initalState: HomeState = {
  channels: [],
  restChannels: [],
  activeId: 0,
  channelsArticle: {},
}

const home = (state = initalState, action: RootAction): HomeState => {
  switch (action.type) {
    // 获取频道数据
    case 'Home/getChannels':
      return {
        ...state,
        channels: action.payload,
      }

    // 获取所有的可选频道
    case 'Home/getRestChannels':
      return {
        ...state,
        restChannels: action.payload,
      }
    // 切换高亮
    case 'Home/changeChannels':
      return {
        ...state,
        activeId: action.payload,
      }
    // 删除个人频道
    case 'Home/delMyChannels':
      return {
        ...state,
        channels: state.channels.filter(
          (item) => item.id !== action.payload.id
        ),

        // 运用lodash进行排序
        restChannels: sortBy([...state.restChannels, action.payload], 'id'),
      }

    // 增加个人频道
    case 'Home/addChannels':
      return {
        ...state,
        channels: [...state.channels, action.payload],
        restChannels: state.restChannels.filter(
          item => item.id !== action.payload.id
        ),
      }

    //追加文章列表数据
    case 'Home/getChannelsIdList':
      const {
        articleList: { pre_timestamp, results },
        channelId,
      } = action.payload

      const currentResults = state.channelsArticle[channelId]?.results ?? []
      return {
        ...state,

        //只修改:频道文章列表数据
        channelsArticle: {
          // 展开所有频道的列表数据
          ...state.channelsArticle,
          // 注意：这是重头戏   数据是要追加的哦
          [channelId]: {
            pre_timestamp,

            results: [
              // 已有的数据
              ...currentResults,
              // 接口返回的数据
              ...results,
            ],
          },
        },
      }

    // 下拉获取最新数据
    case 'Home/getNewestArticleList':
      const {
        channelId: id,
        articleList: { results: res, pre_timestamp: pre },
      } = action.payload

      const currentResultes = state.channelsArticle[id]?.results ?? []

      return {
        ...state,
        channelsArticle: {
          ...state.channelsArticle,
          [id]: {
            pre_timestamp: pre,

            // 注意：该数据要追加
            results: [
              // 接口的新数据
              ...res,

              // 原有的老数据
              ...currentResultes,
            ],
          },
        },
      }

    default:
      return state
  }
}

export default home
